let _Vue = null
export default class VueRouter {
  static install(Vue) {
    // 当前插件是否已经被安装
    if (VueRouter.install.installed) {
      return
    }
    VueRouter.install.installed = true

    // Vue构造函数纪录到全局变量
    _Vue = Vue

    // 创建Vue实例时候传入的router对象注入到Vue实例
    //  混入
    _Vue.mixin({
      beforeCreate() {
        if (this.$options.router) {
          _Vue.prototype.$router = this.$options.router
          this.$options.router.init();
        }
      }
    })
  }

  constructor(options) {
    this.options = options
    this.routeMap = {}
    this.data = _Vue.observable({
      // current: "/"
      current: this.initCurrentPath(options.mode)
    })
  }

  init() {
    this.createRouteMap()
    this.initComponent(_Vue)
    this.initEvent()
  }

  createRouteMap() {
    // 遍历所有的理由规则 把路由规则解析成键值对的形式 存储到routeMap
    this.options.routes.forEach(route => {
      this.routeMap[route.path] = route.component
    })
  }

  initComponent(Vue) {
    Vue.component("router-link", {
      props: {
        to: String
      },
      // template: '<a :hreft="to"><slot></slot></a>'
      render(h) {
        return h('a', {
          attrs: {
            href: this.to
          },
          on: {
            click: this.clickHandler
          }
        }, [this.$slots.default])
      },
      methods: {
        clickHandler(e) {
          if (self.options.mode === "history") {
            this.handlerHistory(e)
          } else {
            this.handlerHash(e)
          }
        },
        handlerHistory(e) {
          // 更新 url
          history.pushState({}, "title", this.to)
          // 更新 VueRouter 中 data.current
          this.$router.data.current = this.to
          e.preventDefault() // 阻止a标签点击事件的默认行为
        },
        handlerHash(e) {
          window.location.hash = this.to
          e.preventDefault()
        }
      }
    })

    const self = this
    Vue.component("router-view", {
      render(h) {
        const cm = self.routeMap[self.data.current] // 当前路径组件
        return h(cm) // 返回渲染
      }
    })
  }

  // 监听事件
  initEvent() {
    window.addEventListener('popstate', () => {
      this.data.current = window.location.pathname
    })

    window.addEventListener('hashchange', () => {
      const url = window.location.hash.substr(1)
      this.data.current = url
    })
  }

  // 判断初始化路径 渲染组件
  initCurrentPath(mode) {
    if (mode === "history") {
      return window.location.pathname
    } else {
      return window.location.hash = window.location.hash ? window.location.hash.substr(1) : '#/'
    }
  }
}